package cn.edu.zut.hhr.filter;

import cn.edu.zut.hhr.utils.RedisUtil;
import cn.edu.zut.hhr.utils.TokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
import org.springframework.stereotype.Component;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

public class TokenAuthFilter extends BasicAuthenticationFilter {

    RedisUtil redisUtil;

    public TokenAuthFilter(AuthenticationManager authenticationManager, RedisUtil redisUtil) {
        super(authenticationManager);
        this.redisUtil = redisUtil;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        UsernamePasswordAuthenticationToken authRequest = getAuthentication(request);
        //写入security上下文
        SecurityContextHolder.getContext().setAuthentication(authRequest);
        chain.doFilter(request,response);
    }

    private UsernamePasswordAuthenticationToken getAuthentication(HttpServletRequest request){
        String token = request.getHeader("token");
        if(token == null){
            return new UsernamePasswordAuthenticationToken("","",new HashSet<>());
        }
        String username = TokenUtil.getUserInfoFromToken(token);
        Set<String> roles = redisUtil.sMembers(username);
        Set<GrantedAuthority> groles = new HashSet<>();
        for(String role: roles){
            groles.add(new SimpleGrantedAuthority(role));
        }
        return new UsernamePasswordAuthenticationToken(username,token,groles);
    }

}
